const path = require('path');
const config = require('./config');
const express = require('express');
const morgan = require('morgan');
const compress = require('compression');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const passport = require('passport');

module.exports = function () {
    const app = express();

    //Change the development mode
    if(process.env.NODE_ENV === 'development') {
        app.use(morgan('dev'));
        app.use(session({
            saveUninitialized: true,
            resave: true,
            secret: config.sessionSecret
        }));
    }else if(process.env.NODE_ENV === 'production') {
        app.use(compress());
        app.use(session({
            secret: config.sessionSecret,
            store: new MongoStore({mongooseConnection: mongoose.connection,
            ttl: 1 * 24 * 60 * 60})
        }))
    }

    //Parsers for Post data
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.use(passport.initialize());
    app.use(passport.session());

    //add your configurable routes here
    require('../routes/user.server.routes')(app);
    require('../routes/article.server.routes')(app);

    // Catch all other routes and return the index file
    app.get('/', (req, res)=> {
        if (req.session.lastVisit) {
            console.log(req.session.lastVisit);
        }
        req.session.lastVisit = new Date();
        res.sendFile(path.join(__dirname, '../dist/index.html'));
    });

    //Point static path to dist(must to be latest)
    app.use(express.static(path.join(__dirname, '../dist')));
    return app;
};

